package com.hzsai.aspect;

import com.hzsai.utils.JSONUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;


/**
 * hzsai 2019/8/29
 * usage: 全局Controller拦截器，日志记录
 **/
@Aspect
@Component
public class HttpLog {

    private static final Logger logger = LoggerFactory.getLogger(HttpLog.class);

    private ThreadLocal<Long> startTime = new ThreadLocal<>();

    // controller包下的所有方法，方法可以带任意参数
    @Pointcut("execution(* com.hzsai.controller.*.*(..))")
    public void pointCut() {
    }

    @Before("pointCut()")
    public void doBefore(JoinPoint joinPoint) {
        startTime.set(System.currentTimeMillis());

        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attributes.getRequest();

        // URL
        logger.debug("url: {}", request.getRequestURL());
        // Request method, GET, POST, DELETE...
        logger.debug("method: {}", request.getMethod());
        // IP
        logger.debug("IP: {}", request.getRemoteAddr() + " : " + request.getRemoteHost());
        // class method name
        logger.debug("method: {}", joinPoint.getSignature().getDeclaringTypeName()  + "." + joinPoint.getSignature().getName());
        // args
        // TODO:
        //  BUG HERE!!!部分参数情况下不能解析正常
        logger.debug("args: {}", JSONUtil.toJSONString(joinPoint.getArgs()));
    }

    @After("pointCut()")
    public void doAfter() {
        logger.debug("Request used: {}ms", System.currentTimeMillis() - startTime.get());
    }

    /**
     * ??????
     * 拦截参数部分会有问题，需过滤比如HttpServletRequest request这样的参数
     * 因为在有JSONUtil解析部分会出错
     */
    @AfterReturning(returning = "object", pointcut = "pointCut()")
    public void doReturn(Object object) {
        logger.debug("response: {}", JSONUtil.toJSONString(object));
    }
}
